//
//  NewsViewController.swift
//  OSCChina
//
//  Created by 刘威 on 2016/11/29.
//  Copyright © 2016年 刘威. All rights reserved.
//

import UIKit
import Alamofire
import MJRefresh
import YYModel
import YYCache

let sizeScale = ((UIScreen.main.bounds.height > 568) ? (UIScreen.main.bounds.height/568)  : 1) //屏幕字体缩放比例 参考值568

let titleFontSize:CGFloat = 15
let contentFontSize:CGFloat = 13

enum NewsType:NSInteger {
    case Software = 1
    case QueAns = 2
    case Blog = 3
    case Translation = 4
    case Activity = 5
    case Info = 6
}

class NewsViewController: UIViewController,XMLParserDelegate,UITableViewDelegate,UITableViewDataSource {
    
    var NewsList:[NewsModel] = []
    var tableView:UITableView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let news_api = "https://www.oschina.net/action/apiv2/news"
        //let news_list_api = "https://www.oschina.net/action/api/news_list"
        
        self.initDataTable()
        self.tableView?.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            
            self.getNews(url: news_api)
        })
        self.tableView?.mj_header.beginRefreshing()
    }
    
    func getNews(url:String){
        
        let cache = YYCache(name: "newsCache")
        cache?.memoryCache.shouldRemoveAllObjectsOnMemoryWarning = true
        cache?.memoryCache.shouldRemoveAllObjectsWhenEnteringBackground = true
        let object = cache!.object(forKey: url)
        
        Alamofire.request(url).responseJSON { response in
            switch response.result{
            case.success(let json):
                
                //print("news json:\(json)")
                cache?.setObject(json as? NSCoding, forKey: url)
                self.parserData(json as! Dictionary<String,AnyObject>)
                
            case.failure(let error):
                
                if (object != nil) {
                    
                    self.parserData(object as! Dictionary<String,AnyObject>)
                }
                print("error:\(error)")
            }
            
            self.tableView!.mj_header.endRefreshing();
        }
    }
    
    func parserData(_ data: Dictionary<String,AnyObject>){
        let dict = data
        let items = dict["result"]!["items"] as! NSArray;
        for o in items {
            let model = NewsModel.yy_model(with: o as! Dictionary<String,AnyObject>)
            self.NewsList.append(model!)
        }
        self.tableView?.reloadData()
    }
    
    func initDataTable(){
        
        self.tableView = UITableView()
        self.tableView?.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width,height:UIScreen.main.bounds.height)
        self.tableView!.dataSource = self
        self.tableView!.delegate = self
        self.tableView?.tableFooterView = UIView()
        self.tableView?.rowHeight = UITableViewAutomaticDimension
        self.tableView?.estimatedRowHeight = 80
        let cellNib = UINib(nibName: "NewsTableViewCell", bundle: nil)
        self.tableView!.register(cellNib, forCellReuseIdentifier: "newsIdentifier")
        self.view.addSubview(self.tableView!)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.NewsList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:NewsTableViewCell =  tableView.dequeueReusableCell(withIdentifier: "newsIdentifier", for: indexPath) as!NewsTableViewCell
        
        let news = self.NewsList[indexPath.row] 
        
        cell.titleLabel.text = news.title
        cell.contentLabel.text = news.body
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let news = self.NewsList[indexPath.row]
        let detailVC = NewsDetailViewController()
        detailVC.blogId = news.id
        detailVC.newsType = NewsType(rawValue: news.type)!
        
        self.navigationController?.pushViewController(detailVC, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

